/*!
 * Ext JS Library 3.3.1
 * Copyright(c) 2006-2010 Sencha Inc.
 * licensing@sencha.com
 * http://www.sencha.com/license
 */
// Application instance for showing user-feedback messages.
//var App = new Ext.App({});
var fm = Ext.form;
var base_url = '<?php echo base64_decode($_GET['baseUrl']);?>';
var order_status = '<?php echo $_GET['status'];?>';
var total_row = 50;
var proxy = new Ext.data.ScriptTagProxy({
 	api: {
        read : base_url+'admin/order_management/order_grid.html?status='+order_status,
        create : base_url+'admin/order_management/add_order.html',
        update: base_url+'admin/order_management/add_order.html',
        destroy: base_url+'admin/order_management/delete_order.html'
    }
});
/*proxy.addListener('beforeload', function(scriptProxy,params){
	offset = params.start;
});*/
// The new DataWriter component.
var writer = new Ext.data.JsonWriter({
    encode: true   // <-- don't return encoded JSON -- causes Ext.Ajax#request to send data using jsonData config rather than HTTP params
});

// Typical Store collecting the Proxy, Reader and Writer together.
var store = new Ext.data.JsonStore({
    //id: 'id',
    //restful: true,     // <-- This Store is RESTful
	start : 'start',
	remoteSort: true,
    totalProperty: 'total',
    proxy: proxy,
    root: 'data',
    fields : [
              {name: 'id'},
              {name: 'order_day', type: 'date'},
              {name: 'arrival_day', type: 'date'},
              {name: 'email', allowBlank: false},
              {name: 'number_of_applicant'},
              {name: 'view',type: 'string'},
              {name: 'status',type: 'string'}
          ],
	  listeners: {
	      save: function(s, b, d) {
	    	  store.save();
	      }
	  },  
    writer: writer    // <-- plug a DataWriter into the store just as you would a Reader
});

// load the store immeditately
//store.load();

var filters = new Ext.ux.grid.GridFilters({
    // encode and local configuration options defined previously for easier reuse
    encode: true, // json encode the filter query
    local: true,   // defaults to false (remote filtering)
    filters: [{
        type: 'numeric',
        dataIndex: 'id'
    }, {
        type: 'date',
        dataIndex: 'order_day'
    }, {
        type: 'date',
        dataIndex: 'arrival_day'
    }, {
        type: 'string',
        dataIndex: 'email',
        disabled: true
    }, {
        type: 'numeric',
        dataIndex: 'number_of_applicant'
    }, {
        type: 'string',
        dataIndex: 'view',
        disabled: true
    }, {
        type: 'list',
        dataIndex: 'status',
       // options: [[1,'new'],[2,'proccessing'],[3,'finished']],
        options: ['new','proccessing','finished'],
        phpMode: true
    }]
});
var createColModel = function (finish, start) {

    var columns = [{header: "ID", 
                	width: 40, 
                	sortable: true,
                	sort: 'id', 
                	dataIndex: 'id'
                },{
                	header: "Order day",
                	renderer: formatDate, 
                	width: 95, 
                	sortable: true,
                	sort: 'order_day', 
                	dataIndex: 'order_day', 
                	editor: new fm.DateField({
                       format: 'd-m-Y'
                   })
                },{
                	header: "Arrival day",
                	renderer: formatDate, 
                	width: 95, 
                	sortable: true,
                	sort: 'arrival_day',
                	dataIndex: 'arrival_day', 
                	editor: new fm.DateField({
                       format: 'd-m-Y'
                   })
                },{
                	header: "Email", 
                	width: 100, 
                	sortable: true, 
                	sort: 'email',
                	dataIndex: 'email', 
                	editor: new Ext.form.TextField({})
                },{
                	header: "Number of applicant", 
                	width: 50,  
                	sortable: true,
                	sort: 'number_of_applicant',
                	dataIndex: 'number_of_applicant', 
                	editor: new fm.NumberField({
                       maxValue: 100000
                   })
                },{
                	header: "View", 
                	width: 100, 
                	sortable: true,
                	sort: 'id',
                	dataIndex: 'view'
                },{
                	header: "Status",
                	//renderer: formatStatus, 
                	width: 50, 
                	sortable: false,
                	dataIndex: 'status', 
                	editor: new fm.ComboBox({
                	   editable: false,
                       typeAhead: true,
                       triggerAction: 'all',
                       // transform the data already specified in html
                       transform: 'status',
                       lazyRender: true,
                       listClass: 'x-combo-list-small'
                   })
               }
               ];

    return new Ext.grid.ColumnModel({
        columns: columns.slice(start || 0, finish),
        defaults: {
            sortable: true
        }
    });
};

Ext.onReady(function() {
    Ext.QuickTips.init();

    // use RowEditor for editing
    var editor = new Ext.ux.grid.RowEditor({
        saveText: 'Update'
    });
    // Create a typical GridPanel with RowEditor plugin
    var ordersGrid = new Ext.grid.GridPanel({
        renderTo: 'orders-grid',
        iconCls: 'icon-grid',
        frame: true,        
        height: eval(Ext.getBody().getViewSize().height - 280),
        store: store,
        plugins: [editor,filters],
        colModel: createColModel(7),
        listeners: {
            render: {
                fn: function(){
                    store.load({
                        params: {
                            start: 0,
                            limit: total_row
                        }
                    });
                }
            }
        },
        tbar: [/*{
            text: 'Add',
            iconCls: 'silk-add',
            handler: onAdd
        }, '-', */{
            text: 'Delete',
            iconCls: 'silk-delete',
            handler: onDelete
        }, '-'],
        bbar: new Ext.PagingToolbar({
            store: store,
            pageSize: total_row,
            plugins: [filters]
        }),
        viewConfig: {
            forceFit: true
        }

    });

    /**
     * onAdd
     */
   /* function onAdd(btn, ev) {
        var u = new ordersGrid.store.recordType();
        editor.stopEditing();
        ordersGrid.store.insert(0, u);
        editor.startEditing(0);
    }*/
    /**
     * onDelete
     */
    function onDelete() {
        var recs = ordersGrid.getSelectionModel().getSelections() ;
        if (!recs) {
            return false;
        }
        for(var i in recs)
        {
            ordersGrid.store.remove(recs[i]);
        }
    }
    //store.on();

});
function formatDate(value){
    return value ? value.dateFormat('d-m-Y') : '';
}
/*function formatStatus(value){
	var txtVal ='';
	switch(value){	
	case 1: txtVal = 'New';
			break;
	case 2:	txtVal = 'Processing';
			break;
	case 3: txtVal = 'Finished';
			break;
			
	}
	return txtVal;
}*/
function thickBoxPopup(id){
	tb_show('Order details',base_url+'admin/order_management/details_order.html?id='+id+'&width=600');
	if(order_status=='new')
		store.load({
	                        params: {
	                            start: 0,
	                            limit: total_row
	                        }
	                    });
	//alert('aaa');
}
